﻿using System;
using System.Collections.Generic;

using Microsoft.Practices.EnterpriseLibrary.Validation;

using VabValidationResults = Microsoft.Practices.EnterpriseLibrary.Validation.ValidationResults;
using VabValidationResult = Microsoft.Practices.EnterpriseLibrary.Validation.ValidationResult;
using ValidationResults = Framework.Validation.Implementation.ValidationResults;

namespace Framework.Validation.Vab
{
    /// <summary>
    /// Provides ability to work with <see cref="Validator" /> as with <see crf="IValidator" />.
    /// </summary>
    public class VabValidatorWrapper : IValidator
    {
        private readonly Validator validator;

        /// <summary>
        /// Initializes a new instance of the <see cref="VabValidatorWrapper"/> class.
        /// </summary>
        /// <param name="validator">The <see cref="Validator" /> instance.</param>
        public VabValidatorWrapper(Validator validator)
        {
            if (validator == null)
            {
                throw new ArgumentNullException("validator");
            }

            this.validator = validator;
        }

        private static void GatherResults(
            IEnumerable<VabValidationResult> vabResults,
            ValidationResults results)
        {
            foreach (VabValidationResult vabResult in vabResults)
            {
                VabValidationResultWrapper vabResultWrapper = vabResult
                    as VabValidationResultWrapper;
                if (vabResultWrapper != null)
                {
                    GatherResults(vabResultWrapper.NestedValidationResults, results);
                    results.Add(vabResultWrapper.ValidationResult);
                }
            }
        }

        /// <inheritdoc />
        public IValidationResults Validate(object validatable)
        {
            VabValidationResults vabResults = validator.Validate(validatable);

            ValidationResults results = new ValidationResults();
            GatherResults(vabResults, results);

            return results;
        }
    }
}
